﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UpdateHYLiveShowConsole.Dto;

namespace UpdateHYLiveShowConsole
{
    class Program
    {
        static readonly Thread[] _threads = new Thread[1];
        static void Main(string[] args)
        {
            Console.WriteLine("按1，完全更新文件");
            var input = "";
            while (input != "0")
            {
                input = Console.ReadLine();
                switch (input)
                {
                    case "1":
                        Console.WriteLine("输入绝对位置，不输入采用程序位置");
                        var path = Console.ReadLine();
                        UpdateLatest(path);
                        break;
                }

            }
        }

        static void UpdateLatest(string path = null)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                path = System.AppDomain.CurrentDomain.BaseDirectory; 
            }

            if (path.Last() != '\\')
            {
                path = path + '\\';
            }
            DirectoryInfo folder = new DirectoryInfo(path);
            var files = folder.GetFiles();
            var start = 1;
            var row = 100;
            
            var countOfProgram = 0;
            IDictionary<string, string> downloadDic = new Dictionary<string, string>();
            do
            {
                var url = Source.GetSource(start, row);
                var result = HttpRequestHelper.GetRequestStr(url, "");
                start++;
                result = result.Substring(result.IndexOf('(') + 1);
                result = result.Substring(0, result.LastIndexOf(')'));
                var resultDto = Utility.JsonWrapper.Decode<Rootobject>(result);

                var programs = resultDto.data.program;
                countOfProgram = programs.Length;
                
                foreach (var program in programs)
                {
                    if (program.downloadUrl.Contains("hyxcx_1451878614028wyzs_1452157204037"))
                    {
                        var asd = 1;
                    }
                    var programName = program.name + program.downloadUrl.Substring(program.downloadUrl.LastIndexOf('.'));
                    var hasTheSameFile = false;
                    var onlineFileName = program.downloadUrl.Substring(program.downloadUrl.LastIndexOf('/') + 1);
                    foreach (var file in files)
                    {
                        var equalToOnlineName = file.Name.Equals(onlineFileName);
                        if (equalToOnlineName || file.Name.Equals(programName))
                        {
                            hasTheSameFile = true;
                            Console.WriteLine("跳过："+file.Name);
                            if (equalToOnlineName)
                            {
                                file.MoveTo(path + programName);
                                Console.WriteLine("重命名："+ programName);
                            }
                            break;
                        }
                    }
                    if (hasTheSameFile)
                    {
                        continue;
                    }
                    var downloadPath = path + programName;
                    downloadDic[program.downloadUrl] = downloadPath;

                }
            } while (countOfProgram >= row);

            Console.WriteLine("需要下载 " + downloadDic.Count + " 个文件");
            foreach (var download in downloadDic)
            {
                var downloadUrl = download.Key;
                var downloadPath = download.Value;
                var threadIndex = GetThreadIndex();
                ThreadStart threadStart = new ThreadStart(delegate ()
                {
                    var now = DateTime.Now;
                    Console.WriteLine("下载中" + (threadIndex + 1) + "：" + downloadUrl + " " + downloadPath);
                    var result = HttpRequestHelper.HttpDownload(downloadUrl, downloadPath);
                    var finish = DateTime.Now;
                    if(result)
                        Console.WriteLine("下载完" + (threadIndex + 1) + "：" + downloadPath + "耗时：" + (finish - now));
                    else
                        Console.WriteLine("下载失败" + (threadIndex + 1) + "：" + downloadUrl + "耗时：" + (finish - now));
                });

                _threads[threadIndex] = new Thread(threadStart);
                _threads[threadIndex].Start();
            }

            while (_threads.Any(d=>d.ThreadState != ThreadState.Stopped))
            {
                Thread.Sleep(100);
            }
            Console.WriteLine("下载完成");
        }

        public static int GetThreadIndex()
        {
            while (true)
            {
                for (var index = 0; index < _threads.Length; index++)
                {
                    if (_threads[index] == null || _threads[index].ThreadState == ThreadState.Stopped)
                        return index;
                }

                Thread.Sleep(100);
            }

        }
    }
}
